﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace 深入浅出WPF_Chapter8路由事件
{
    /// <summary>
    /// Interaction logic for Sample2.xaml
    /// </summary>
    public partial class Sample2 : Window
    {
        public Sample2()
        {
            InitializeComponent();
        }

        private void ReprotTimeHandler(object sender, ReportTimeEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            
            //按钮被单击的时间
            //string timeStr=e.ClickTime.ToLongTimeString();
            //string timeStr = e.ClickTime.ToString("HH:mm:ss.ffffff");
            
            //事件到达时间
            string timeStr = DateTime.Now.ToString("HH:mm:ss.fffffff"); //最多7位
            string content = string.Format("{0} 到达 {1}", timeStr, element.Name);
            this.listBox.Items.Add(content);

            //默认情况下，如果两个非记录引用类型操作符引用同一对象，则这两个操作符相等
            if (element == this.grid_2)
            {
                e.Handled = true;
            }
        }
    }

    //用于承载时间消息的事件参数
    class ReportTimeEventArgs : RoutedEventArgs
    {
        public ReportTimeEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
        
        public DateTime ClickTime { get; set; }
    }

    class TimeButton : Button
    {
        //声明和注册路由事件
        public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent("ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeEventArgs>), typeof(TimeButton));

        //CLR事件包装器
        public event RoutedEventHandler ReportTime
        {
            add { this.AddHandler(ReportTimeEvent, value); }
            remove { this.RemoveHandler(ReportTimeEvent, value); }
        }

        //激发路由事件，借用Click事件的激发方法
        protected override void OnClick()
        {
            base.OnClick(); //保证button 原有功能正常使用、Click事件能被激发

            ReportTimeEventArgs args = new ReportTimeEventArgs(ReportTimeEvent, this);
            args.ClickTime = DateTime.Now;
            this.RaiseEvent(args);
        }
    }
}
